package com.xinyue.exceltool.logic.convert.impl;

import com.alibaba.fastjson.JSONArray;
import com.xinyue.exceltool.logic.convert.ICellValueTypeStrategy;
import com.xinyue.exceltool.logic.convert.ValueConvertUtil;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 王广帅
 * @since 2021/5/8 23:25
 */
public class IntArrayConvert implements ICellValueTypeStrategy {

    @Override
    public Object convert(String value) {
        if (StringUtils.isEmpty(value)) {
            return null;
        }
        if (value.startsWith("[")) {
            JSONArray jsonArray = JSONArray.parseArray(value);
            List<Integer> intData = jsonArray.toJavaList(Integer.class);
            return intData;
        } else {
            //兼容一下中文逗号，虽然强调让策划和数值配置的时候要用英文逗号，但是他们也有可能不按约定来
            String tempValue = ValueConvertUtil.replaceChineseComma(value);
            String[] strData = ValueConvertUtil.splitByComma(tempValue);
            //对于json串来说，int[]和List<Integer> 没什么区别
            List<Integer> intData = Arrays.stream(strData).filter(s -> s != null).map(s -> Integer.parseInt(s)).collect(Collectors.toList());
            return intData;
        }
    }

    @Override
    public String getJavaFieldTypeName(String type) {
        return "List<Integer>";
    }

    @Override
    public String getImpartPackage() {
        return "import java.util.List;";
    }

    @Override
    public boolean isDbJson() {
        return true;
    }
}
